package li.brauch.semesterarbeit.radio.sound;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.BooleanControl;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Port;

public class Volume {
	
	private Line lineOut;
	private FloatControl volumeControl;
	private BooleanControl muteControl;
	
	public Volume() throws Exception {
		try {
			if(AudioSystem.isLineSupported(Port.Info.LINE_OUT)) {
				lineOut = (Port)AudioSystem.getLine(Port.Info.LINE_OUT);
				lineOut.open();
			} else if(AudioSystem.isLineSupported(Port.Info.HEADPHONE)) {
				lineOut = (Port)AudioSystem.getLine(Port.Info.HEADPHONE);
				lineOut.open();
			} else if(AudioSystem.isLineSupported(Port.Info.SPEAKER)) {
				lineOut = (Port)AudioSystem.getLine(Port.Info.SPEAKER);
				lineOut.open();
			} else {
				throw new Exception("Unable to get volume control");
			}
			
			volumeControl = (FloatControl) lineOut.getControl(FloatControl.Type.VOLUME);
			muteControl = (BooleanControl) lineOut.getControl(BooleanControl.Type.MUTE);

		} catch (LineUnavailableException e) {
			throw new Exception(e.getMessage());
		}
		
	}
	
	public void setVolume(int volume) {
		if (volume > -1 && volume < 101)
			volumeControl.setValue((float) volume / 100);
	}
	
	public int getVolume() {
		return Math.round(100 * volumeControl.getValue() / volumeControl.getMaximum());
	}
	
	public void toggleMute() {
		boolean value = muteControl.getValue();
		muteControl.setValue(!value);
	}
	
	public boolean isMute() {
		return muteControl.getValue();
	}
	
	public void close() {
		lineOut.close();
	}
	
	
}
